<?php
class Controller_Admin_Estimate extends  Controller_Template {
	public function __construct($req, $res) {
		$this->template = "smarty:admin/estimate/budgets";
		parent::__construct($req, $res);
	}

	/**
	 * 获得所有的历史结算数据
	 *
	 *
	 */	
	public function action_history()
	{
	 	$mer_id = User::current_user_id();
		$tno = date('Ym');
		$rs = array();
        $vendor    = new Promotion_Vendor(user::current_user_id());
		$activites = $vendor->get_activity($mer_id);
		foreach($activites as $key => $val)
		{
			$activity = Promotion_Activity::info($val['activity_id']);
			$budget = Estimate_Budget::budget_info($tno,$val['activity_id'],$mer_id);
			$rs[$key]['month'] = $budget['no'];
			$rs[$key]['money'] = $budget['money'];
			$rs[$key]['counts'] = $budget['counts'];
			$rs[$key]['pay_type'] = $budget['pay_type'];
			$rs[$key]['activity_name'] = $activity['name'];
			$rs[$key]['status'] = $budget['status'];
		}

		$this->template->set_filename('smarty:estimate/budgets');
		$this->template->set('rs',$rs);
	}

    /**
     * 当前结算信息
     */
    public function action_current ()
    {
        $this->template->set('estimates', estimate::lists(user::current_user_id()));
        $this->template->set_filename('smarty:estimate/list');
    }

	public function action_build_budget()
	{
		$start_date = $this->request->query('start_date');
		$end_date = $this->request->query('end_date');
		$tno = $this->request->query('tno'); 
        $act = $this->request->query('activity_id');

        if (empty($act))
            throw new Exception("CPA活动参数错误");

		if ($tno == NULL)
		{
			$tno = date('Ym');
		}
		
		if($start_date == NULL){
			$start_date = date('Y-m-d', strtotime('-30 days'));
		}
		if($end_date == NULL){
			$end_date = date('Y-m-d');
		}

        $CPA_acts = array($act);
        foreach ($CPA_acts as $cpa_act_id)
        {
            $budget = new Estimate_Budget();
            $budget->build($tno,$start_date,$end_date, $cpa_act_id);
            echo "<P>$apa_act_id Budget finished</p>\n";
        }
	}


	public function action_budgets()
	{
		$user = User::current_user_info();
		$act_ids = array();
		if($user->role_id != 'suppermanager'){
			$activities = Promotion_Activity::get_activity_creater_id($user->uid);
			foreach($activities as $val)
			{
				$act_ids[] = $val['id'];
			}
		}
		$query = array(
			'include_merchant_info' => TRUE,
			'include_activity_info' => TRUE,
		);	
		if(!empty($act_ids)){
			$query['activity_id'] = $act_ids;
		}
		$rs = Estimate_Budget::search($query);
		$this->template->set_filename('smarty:admin/estimate/budgets');
		$this->template->set('rs',$rs);
	}


}
